import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:material_collection_app/utils/dio_utils.dart';
import 'package:material_collection_app/utils/event_bus_util.dart';
import 'package:material_collection_app/utils/utils.dart';
import 'package:material_collection_app/widget/common/dialog_task.dart';
import 'package:material_collection_app/widget/common/empty_tips.dart';
import 'package:material_collection_app/widget/common/refresh.dart';
import 'package:material_collection_app/widget/enter/enter_item.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

GlobalKey<_EnterTabPageState> acceptKey = GlobalKey();
GlobalKey<_EnterTabPageState> checkKey = GlobalKey();
GlobalKey<_EnterTabPageState> checkedKey = GlobalKey();

class EnterTabPage extends StatefulWidget {
  final String baseApi; // 接口前缀
  final String status; // tab页标识
  final String keywords; //搜索关键字
  // List list;

  // EnterTabPage({Key key, this.baseApi = 'enter/', this.status, this.keywords, this.list}) :super(key:key);
  EnterTabPage({Key key, this.baseApi = 'enter/', this.status, this.keywords})
      : super(key: key);

  @override
  _EnterTabPageState createState() => _EnterTabPageState();
}

class _EnterTabPageState extends State<EnterTabPage>
    with AutomaticKeepAliveClientMixin {
  List list = [];
  int currentPage = 1;
  int lastPage = 1;
  bool loadSuccess = false;
  var eventBus = new EventBus();
  RefreshController _refreshController =
      RefreshController(initialRefresh: false);
  //页面无数据的刷新控件
  RefreshController _emptyRefreshController =
      RefreshController(initialRefresh: false);

  String baseApi = 'enter/';

  @override
  bool get wantKeepAlive => true;

  @override
  void initState() {
    super.initState();
    setState(() {
      baseApi = widget.baseApi;
    });
    _loadData();

    eventBus.on("enter_check", (parmas) {
      setState(() {
        list.removeAt(parmas['index']);
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
    eventBus.off("enter_check");
  }

  // 搜索
  void search() {
    Timer.periodic(Duration(milliseconds: 50), (timer) {
      _loadData();
      timer.cancel();
    });
  }

  // 加载数据
  void _loadData({bool loadMore = false}) async {
    loadSuccess = false;

    if (loadMore) {
      currentPage++;
    } else {
      currentPage = 1;
    }

    DioUtils.request("${baseApi}getlist",
        context: context,
        method: "POST",
        params: {
          'current_page': currentPage,
          'status': widget.status,
          'keywords': widget.keywords,
        }, onSuccess: (res) {
      if (res['code'] == 1) {
        if (mounted) {
          setState(() {
            if (loadMore) {
              list.addAll(res["data"]["data"]);
            } else {
              list = res["data"]["data"];
            }
            currentPage = res['data']['current_page'];
            lastPage = res['data']['last_page'];
            loadSuccess = true;
          });
        }
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  // 下拉刷新
  void _onRefresh() async {
    _refreshController.loadComplete();
    _emptyRefreshController.loadComplete();
    _loadData();

    await Future.delayed(Duration(milliseconds: 600));
    _refreshController.refreshCompleted();
    _emptyRefreshController.refreshCompleted();
  }

  // 加载更多
  void _onLoading() async {
    await Future.delayed(Duration(milliseconds: 300));

    if (currentPage == lastPage) {
      _refreshController.loadNoData();
      return;
    }

    // 加载更多数据
    if (currentPage < lastPage) {
      _loadData(loadMore: true);
      _refreshController.loadComplete();
    }
  }

  // 接受任务
  void _receiveTask(int id, int index, Map item) {
    DioUtils.request("${baseApi}receive",
        context: context, method: "POST", params: {'id': id}, onSuccess: (res) {
      if (res['code'] == 1) {
        // _showTaskDialog(id);
        setState(() {
          list.removeAt(index);
        });
      } else {
        Utils.showText(text: res['msg']);
      }
    }, onError: (error) {});
  }

  // 接受任务弹窗
  Future<void> _showTaskDialog(int id) async {
    showDialog(
        context: context,
        builder: (BuildContext context) {
          return DialogTask(id: id, showButton: true);
        });
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, width: 750, height: 1334, allowFontScaling: false);

    // 无数据
    if (loadSuccess && list.length == 0) {
      return EmptyTips(
        refreshController: _emptyRefreshController,
        onRefresh: _onRefresh,
      );
    }

    return Container(
        width: 500.w,
        height: 270.w,
        color: Utils.hexToColor('#F5F6FA'),
        child: Refresh(
            refreshController: _refreshController,
            onRefresh: _onRefresh,
            onLoading: _onLoading,
            child: ListView.builder(
                itemCount: list.length,
                padding: EdgeInsets.only(bottom: 60.w),
                itemBuilder: (BuildContext context, int index) {
                  var item = list[index];

                  return EnterItem(
                    baseApi: baseApi,
                    item: item,
                    itemIndex: index,
                    status: widget.status,
                    receiveTask: _receiveTask,
                  );
                })));
  }
}
